<template>
  <div class="game-container">
    <canvas ref="gameCanvas" width="400" height="400" class="game-canvas"></canvas>
    <div class="game-info">
      <p>分数: {{ score }}</p>
      <div class="speed-control">
        <label>速度: {{ Math.floor(1000 / gameSpeed.value) }}格/秒</label>
        <input 
          type="range" 
          :min="50" 
          :max="300" 
          :value="150" 
          @input="e => {
            gameSpeed.value = e.target.value;
          }" 
        />
      </div>
      <button @click="startGame" v-if="!isGameRunning">开始游戏</button>
      <p v-if="gameOver">游戏结束！</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const gameCanvas = ref(null);
const ctx = ref(null);
const snake = ref([{ x: 10, y: 10 }]);
const food = ref({ x: 5, y: 5 });
const direction = ref('right');
const score = ref(0);
const isGameRunning = ref(false);
const gameOver = ref(false);
const gameLoop = ref(null);

const gridSize = 20;
const gameSpeed = ref(150);

const startGame = () => {
  snake.value = [{ x: 10, y: 10 }];
  direction.value = 'right';
  score.value = 0;
  gameOver.value = false;
  isGameRunning.value = true;
  generateFood();
  gameLoop.value = setInterval(updateGame, gameSpeed.value);
};

const generateFood = () => {
  food.value = {
    x: Math.floor(Math.random() * (400 / gridSize)),
    y: Math.floor(Math.random() * (400 / gridSize))
  };
};

const updateGame = () => {
  const newHead = { ...snake.value[0] };

  switch (direction.value) {
    case 'up': newHead.y--; break;
    case 'down': newHead.y++; break;
    case 'left': newHead.x--; break;
    case 'right': newHead.x++; break;
  }

  // 检查碰撞
  if (checkCollision(newHead)) {
    endGame();
    return;
  }

  snake.value.unshift(newHead);

  // 检查是否吃到食物
  if (newHead.x === food.value.x && newHead.y === food.value.y) {
    score.value += 10;
    generateFood();
  } else {
    snake.value.pop();
  }

  drawGame();
};

const checkCollision = (head) => {
  // 检查墙壁碰撞
  if (head.x < 0 || head.x >= 400 / gridSize ||
      head.y < 0 || head.y >= 400 / gridSize) {
    return true;
  }

  // 检查自身碰撞
  return snake.value.some(segment =>
    segment.x === head.x && segment.y === head.y
  );
};

const drawGame = () => {
  if (!ctx.value) return;

  // 清空画布
  ctx.value.clearRect(0, 0, 400, 400);

  // 绘制蛇
  ctx.value.fillStyle = '#42b883';
  snake.value.forEach(segment => {
    ctx.value.fillRect(
      segment.x * gridSize,
      segment.y * gridSize,
      gridSize - 1,
      gridSize - 1
    );
  });

  // 绘制食物
  ctx.value.fillStyle = '#ff6b6b';
  ctx.value.fillRect(
    food.value.x * gridSize,
    food.value.y * gridSize,
    gridSize - 1,
    gridSize - 1
  );
};

const endGame = () => {
  clearInterval(gameLoop.value);
  isGameRunning.value = false;
  gameOver.value = true;
};

const handleKeydown = (e) => {
  if (!isGameRunning.value) return;

  switch (e.key) {
    case 'ArrowUp':
      e.preventDefault();
      if (direction.value !== 'down') direction.value = 'up';
      break;
    case 'ArrowDown':
      e.preventDefault();
      if (direction.value !== 'up') direction.value = 'down';
      break;
    case 'ArrowLeft':
      e.preventDefault();
      if (direction.value !== 'right') direction.value = 'left';
      break;
    case 'ArrowRight':
      e.preventDefault();
      if (direction.value !== 'left') direction.value = 'right';
      break;
  }
};

onMounted(() => {
  ctx.value = gameCanvas.value.getContext('2d');
  window.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown);
  if (gameLoop.value) clearInterval(gameLoop.value);
});
</script>

<style scoped>
.game-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.game-canvas {
  border: 2px solid #42b883;
  background-color: #f8f9fa;
}

.game-info {
  text-align: center;
}

button {
  background-color: #42b883;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

button:hover {
  background-color: #3aa876;
}

.speed-control {
  margin: 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.speed-control input[type="range"] {
  width: 200px;
}

.speed-control label {
  color: #42b883;
  font-weight: bold;
}
</style>